package com.tongshu.miaosha.utils;

import com.tongshu.miaosha.redis.KeyPrefix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public final class RedisUtil {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * redis基础数据类型为String
     */
    // 普通缓存获取
    public Object get(KeyPrefix prefix, String key) {
        return key == null ? null : redisTemplate.opsForValue().get(prefix.getPrefix() + key);
    }

    // 普通缓存放入
    public boolean set(KeyPrefix prefix,String key, Object value) {
        try {
            String realKey = prefix.getPrefix() + key;
            int expireSeconds = prefix.expireSeconds();
            if (expireSeconds <= 0) {
                redisTemplate.opsForValue().set(realKey, value);
            } else {
                redisTemplate.opsForValue().set(realKey, value, expireSeconds, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 删除缓存
    public boolean del(KeyPrefix prefix, String key) {
        try {
            String realKey = prefix.getPrefix() + key;
            return redisTemplate.delete(realKey);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 判断缓存Key是否存在
    public boolean exists(KeyPrefix prefix, String key) {
        return key == null ? false : redisTemplate.hasKey(prefix.getPrefix() + key);
    }

    // 自增
    public Long incr(KeyPrefix prefix, String key) {
        String realKey = prefix.getPrefix() + key;
        return redisTemplate.opsForValue().increment(realKey);
    }

    // 自减
    public Long decr(KeyPrefix prefix, String key) {
        String realKey = prefix.getPrefix() + key;
        return redisTemplate.opsForValue().decrement(realKey);
    }
}
